package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.common.MsgResult;
import com.itheima.common.PageResult;
import com.itheima.common.R;
import com.itheima.common.UserResult;
import com.itheima.dao.*;
import com.itheima.dto.LoginDto;
import com.itheima.pojo.*;
import com.itheima.service.SysUserService;
import com.itheima.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.annotation.Resources;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class SysUserServiceImpl extends ServiceImpl<SysUserDao,SysUser> implements SysUserService {
    //@Autowired
    @Resource
    private SysUserDao sysUserDao;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private SysUserRoleDao userRoleMapper;
    @Autowired
    private SysUserPostDao userPostMapper;
    @Autowired
    private SysRoleDao roleMapper;
    @Autowired
    private SysPostDao postMapper;
    @Autowired
    private SysDeptDao deptMapper;

    @Override
    public R login(LoginDto loginDto,String code) {
        //1.判断下参数是否合法
        if (loginDto==null){
            log.info("账号/密码不能为空");
            return new R(0, MsgResult.NULLPOINT,null);
        }
        //2.根据用户名查询用户对象
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getUserName,loginDto.getUserName());
        SysUser user = sysUserDao.selectOne(wrapper);
        if (user==null){
            log.info("账号错误");
            return new R(0,MsgResult.FAIL_LOGIN,null);
        }
        //3.加密密码
        String pwd = DigestUtils.md5DigestAsHex(loginDto.getPassword().getBytes());
        //4.使用加密后的密码和数据库的密码进行匹配校验
        if (!user.getPassword().equals(pwd)){
            log.info("密码错误");
            return new R(0,MsgResult.FAIL_LOGIN,null);
        }
        //判断用户输入的验证码是否正确
        if (!code.equals(loginDto.getCode())){
            log.info("验证码错误");
            return new R(0,MsgResult.WRONG_VERIFICATION,null);
        }
        log.info("登陆成功");
        return new R(1,MsgResult.SUCCESS_LOGIN,user);
    }

    @Override
    public R findList(Integer pageNum, Integer pageSize, SysUser sysUser) {
        IPage<SysUser> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        if (sysUser.getPhonenumber() != null) {
            wrapper.eq(SysUser::getPhonenumber, sysUser.getPhonenumber());
        }
        if (sysUser.getUserName() != null) {
            wrapper.like(SysUser::getUserName, sysUser.getUserName());
        }
        if (sysUser.getStatus() != null) {
            wrapper.eq(SysUser::getStatus, sysUser.getStatus());
        }
        if (sysUser.getCreateTime() != null) {
            wrapper.eq(SysUser::getCreateTime, sysUser.getCreateTime());
        }
        IPage<SysUser> sysUserIPage = sysUserDao.selectPage(page, wrapper);
        PageResult result = new PageResult();
        result.setPageNum(pageNum);
        result.setPageSize(pageSize);
        result.setPages(sysUserIPage.getPages());
        result.setTotal(sysUserIPage.getTotal());
        result.setResults(sysUserIPage.getRecords());
        return new R(1, "查询成功", result);
    }

    @Override
    public R add(SysUser sysUser) {
        //补全数据
        HttpSession session = request.getSession();
        String userName = (String) session.getAttribute("userName");
        sysUser.setCreateBy(userName);
        sysUser.setCreateTime(new Date());
        sysUserDao.insert(sysUser);
        //添加岗位和角色数据到另外两张表
        //添加角色id
        List<Long> roleIds = sysUser.getRoleIds();
        for (Long roleId : roleIds) {
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setUserId(sysUser.getUserId());
            sysUserRole.setRoleId(roleId);
            userRoleMapper.insert(sysUserRole);
        }
        //添加岗位id
        List<Long> postIds = sysUser.getPostIds();
        for (Long postId : postIds) {
            SysUserPost sysUserPost = new SysUserPost();
            sysUserPost.setUserId(sysUser.getUserId());
            sysUserPost.setPostId(postId);
            userPostMapper.insert(sysUserPost);
        }
        return new R(1,"添加成功",null);
    }

    @Override
    public UserResult findRoleAndPost() {
        List<SysPost> sysPosts = postMapper.selectList(null);
        List<SysRole> sysRoles = roleMapper.selectList(null);
        return new UserResult(1,"查询成功",sysRoles,sysPosts);
    }

    @Override
    public UserResult findById(Long userId) {
        //先根据id查询user表里的数据
        SysUser user = sysUserDao.selectById(userId);
        //查询部门名称
        LambdaQueryWrapper<SysDept> wrapper2 = new LambdaQueryWrapper<>();
        wrapper2.eq(SysDept::getDeptId,user.getDeptId());
        SysDept sysDept = deptMapper.selectOne(wrapper2);
        user.setDeptName(sysDept.getDeptName());
        //roleIds
        LambdaQueryWrapper<SysUserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUserRole::getUserId,user.getUserId());
        List<SysUserRole> userRoles = userRoleMapper.selectList(wrapper);
        List<Long> roleIds=new ArrayList<>();
        for (SysUserRole userRole : userRoles) {
            roleIds.add(userRole.getRoleId());
        }
        //postIds
        LambdaQueryWrapper<SysUserPost> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(SysUserPost::getUserId,user.getUserId());
        List<SysUserPost> userPosts = userPostMapper.selectList(wrapper1);
        List<Long> postIds = new ArrayList<>();
        for (SysUserPost userPost : userPosts) {
            postIds.add(userPost.getPostId());
        }
        //roles和posts
        List<SysPost> posts = postMapper.selectList(null);
        List<SysRole> roles = roleMapper.selectList(null);
        UserResult result = new UserResult(1,"操作成功",user,roleIds,postIds,roles,posts);
        return result;
    }

    @Override
    public R modify(SysUser sysUser) {
        //补全数据
        HttpSession session = request.getSession();
        String userName = (String) session.getAttribute("userName");
        sysUser.setUpdateBy(userName);
        sysUser.setUpdateTime(new Date());
        //更新user表中数据
        sysUserDao.updateById(sysUser);
        //将roleIds存入中间表
        //删除中间表中的数据
        LambdaQueryWrapper<SysUserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUserRole::getUserId,sysUser.getUserId());
        userRoleMapper.delete(wrapper);
        //添加roleId数据
        List<Long> roleIds = sysUser.getRoleIds();
        for (Long roleId : roleIds) {
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setUserId(sysUser.getUserId());
            sysUserRole.setRoleId(roleId);
            userRoleMapper.insert(sysUserRole);
        }
        //将postIds存入中间表
        //删除中间表中的数据
        LambdaQueryWrapper<SysUserPost> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(SysUserPost::getUserId,sysUser.getUserId());
        userPostMapper.delete(wrapper1);
        //添加postIds数据
        List<Long> postIds = sysUser.getPostIds();
        for (Long postId : postIds) {
            SysUserPost sysUserPost = new SysUserPost();
            sysUserPost.setUserId(sysUser.getUserId());
            sysUserPost.setPostId(postId);
            userPostMapper.insert(sysUserPost);
        }
        return new R(1,"修改成功",null);
    }

    @Override
    public R deleteById(Long userId) {
        //删除role中间表中的数据
        LambdaQueryWrapper<SysUserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUserRole::getUserId,userId);
        userRoleMapper.delete(wrapper);
        //删除post中间表数据
        LambdaQueryWrapper<SysUserPost> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(SysUserPost::getUserId,userId);
        userPostMapper.delete(wrapper1);
        //删除user表中的数据
        sysUserDao.deleteById(userId);
        return new R(1,"删除成功",null);
    }

    @Override
    public R modifyStatus(Integer number, Long userId) {
        SysUser user = sysUserDao.selectById(userId);
        user.setStatus(number.toString());
        sysUserDao.updateById(user);
        return new R(1,"状态修改成功",null);
    }

    @Override
    public R ResetPassword(Long userId, String password) {
        SysUser user = sysUserDao.selectById(userId);
        user.setPassword(password);
        sysUserDao.updateById(user);
        return new R(1,"密码重置成功",null);
    }
}
